package com.market.cash.device.task

import android.content.Context
import com.market.cash.device.DVSycBuilder
import com.market.cash.device.http.DVRequestManager
import com.market.cash.device.http.DVRequestParams
import com.market.cash.device.http.DVUrlHelper
import com.market.cash.device.services.DVBatteryService
import com.market.cash.utils.log.CashRootLog
import java.util.concurrent.CompletableFuture
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.function.Supplier

class DVBatteryTask(private val context: Context) : Supplier<String> {

    companion object {
        private const val TASK_ID = "TASK_BATTERY"
    }

    override fun get(): String {
        CashRootLog.i("$TASK_ID Running...")

        val url = DVUrlHelper.combineUrl()
        if (url.isNotBlank()) {
            val latch = CountDownLatch(1)
            Executors.newSingleThreadExecutor().submit(AsyncBatteryTask(context, latch, url))
            latch.await()
        }
        return TASK_ID
    }

    private class AsyncBatteryTask(private val context: Context, private val latch: CountDownLatch, private val url: String) : Runnable {
        override fun run() {
            DVBatteryService().get(context, object : DVBatteryService.OnBatteryInfoListener {
                    override fun onFetchSuccess(zipString: String) {
                        val netParams = DVRequestParams(path = DVSycBuilder.pathBty, deviceBatteryGzip = zipString).toEncryptParams()
                        val future = CompletableFuture.supplyAsync {
                            DVRequestManager(url = url, body = netParams, taskId = TASK_ID).doPost()
                            TASK_ID
                        }
                        future.thenRun { latch.countDown() }
                    }
                })
        }
    }
}
